//
//  HLPickturesView.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/3/4.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit

import SDWebImage

private let reuseIndentifer = "cell"

/// 最大的列数
private let maxColumn = 3

/// item之间的距离都设置为10
private let ItemSpeaceMargin:CGFloat = 10

/// item的大小
private let collectionViewItemWH:CGFloat = (UIScreen.width - speaceMagin*2 - ItemSpeaceMargin*(CGFloat(maxColumn - 1))) / CGFloat(maxColumn)

private let itemSize = CGSizeMake(collectionViewItemWH, collectionViewItemWH)

class HLPickturesView: UICollectionView {
    

    
    /// 微博数据模型
    var statuses:HLStatuses? {
        didSet {
            
            prepareUI()
            
            
           self.reloadData()
        }
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    init() {

        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        self.registerClass(HLPickturesViewCell.self, forCellWithReuseIdentifier: reuseIndentifer)
        backgroundColor = UIColor.clearColor()
        
        self.dataSource = self
    }

    // MARK:设置ui相关的操作
    private func prepareUI() {
        
        let size:CGSize = calculateSize()
        
       /// 关于重用的问题 update
        self.snp_updateConstraints(closure: { (make) -> Void in
            make.size.equalTo(size)
        })
        
    }
    
    
    /// 计算大小
    func calculateSize() -> CGSize{
        /*
        collectionView的大小一定得是 一个矩形
        只有4个的时候很特殊
        */
        let count = statuses?.pic_urls?.count ?? 0
        var column = maxColumn // 先设置为最大的列数
        
        if count == 0 {
            return CGSizeZero
        }
        

        if count == 1 {
            var size = CGSize(width: 180, height: 120)
            
            let urlStr = statuses?.storePictureUrl?.first?.absoluteString
            
            // 坑啊 获得图片还可能失败
            if  let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlStr!) {
                print("urlStr:\(urlStr)")
                
                size = image.size
            }
            
            flowLayout.itemSize = size
            flowLayout.minimumInteritemSpacing = 0
            flowLayout.minimumLineSpacing = 0
            
            // 对图片的大小做一定的处理
            if size.width < 40 {
                size.width = 40
            }else if size.width > UIScreen.width*0.5{
                size.width = UIScreen.width*0.5
            }
            
            return size
        }
        
        flowLayout.itemSize = itemSize
        flowLayout.minimumLineSpacing = ItemSpeaceMargin
        flowLayout.minimumInteritemSpacing = ItemSpeaceMargin
        
        if count == 2 || count == 4 {
            column = 2
        }
        
        //根据个数和列数 计算行数
        let row = (count + column - 1)/column
        
        // 计算宽度
        let width = CGFloat(column) * collectionViewItemWH + (CGFloat(column) - 1) * ItemSpeaceMargin
        
        // 计算高度
        let height = CGFloat(row) * collectionViewItemWH + (CGFloat(row) - 1) * ItemSpeaceMargin
        
        // 遇到问题时最好打印一下  确定问题出在哪里 是哪里有问题
        
        return CGSizeMake(width, height)
        
    }
    


}

extension HLPickturesView:UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.statuses?.pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIndentifer, forIndexPath: indexPath) as! HLPickturesViewCell
        
        cell.url = statuses?.storePictureUrl?[indexPath.row]
        
        return cell
    }
    
}


class HLPickturesViewCell: UICollectionViewCell {

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var url: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(url)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.clearColor()
        
        /*
        case ScaleToFill
        case ScaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
        case ScaleAspectFill
        */
        imageView.contentMode  = UIViewContentMode.ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        prepareUI()
    }

    func prepareUI() {
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(UIEdgeInsetsZero)
        }
    }


    private var imageView:UIImageView = UIImageView()

}
